package com.mindcraft.chat.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.chat.client.ShopClient;
import com.mindcraft.chat.client.UserClient;
import com.mindcraft.chat.mapper.ImChatUserFriendMapper;
import com.mindcraft.chat.mapper.ImChatUserMessageMapper;
import com.mindcraft.chat.mapper.UserFriendSkuMapper;
import com.mindcraft.chat.po.ImChatUserFriend;
import com.mindcraft.chat.po.ImChatUserMessage;
import com.mindcraft.chat.po.UserFriendSku;
import com.mindcraft.chat.service.ImChatUserFriendService;
import com.mindcraft.chat.vo.ImChatUserMessageVo;
import com.mindcraft.chat.vo.NewsListVo;
import com.mindcraft.chat.vo.UserFriendVO;
import com.mindcraft.shop.po.SkuInfo;
import com.mindcraft.user.po.McUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ImChatUserFriendServiceImpl extends ServiceImpl<ImChatUserFriendMapper, ImChatUserFriend> implements ImChatUserFriendService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private UserFriendSkuMapper userFriendSkuMapper;
    @Autowired
    private ShopClient shopClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ImChatUserMessageMapper messageMapper;


    @Override
    public List<UserFriendVO> getFriend(String userId) {


        LambdaQueryChainWrapper<ImChatUserFriend> wrapper = lambdaQuery()
                .eq(ImChatUserFriend::getUserId, userId);

        List<ImChatUserFriend> userFriends = wrapper
                .orderByDesc(ImChatUserFriend::getCreateTime)
                .list();
        List<UserFriendVO> userFriendVOS = new ArrayList<>(userFriends.size());
        userFriends.forEach(userFriend -> {
            McUser friend = userClient.getUser(userFriend.getFriendId());
            if (friend != null) {
                UserFriendVO userFriendVO = new UserFriendVO();
                userFriendVO.setId(userFriend.getId());
                userFriendVO.setUserId(userFriend.getUserId());
                userFriendVO.setFriendId(userFriend.getFriendId());
                userFriendVO.setCreateTime(userFriend.getCreateTime());
                userFriendVO.setRemark(StringUtils.hasText(userFriend.getRemark()) ? userFriend.getRemark() : friend.getUsername());
                userFriendVO.setFriendStatus(userFriend.getFriendStatus());
                userFriendVO.setUsername(friend.getUsername());
                userFriendVO.setAvatar(friend.getUserpic());
                userFriendVO.setGender(friend.getSex());
                userFriendVOS.add(userFriendVO);
            }
        });
        return userFriendVOS;

    }


    @Override
    @Transactional
    public MindCraftResult addFriend(ImChatUserFriend imChatUserFriend) {

        Integer count = lambdaQuery()
                .and(wrapper -> wrapper.eq(ImChatUserFriend::getUserId, imChatUserFriend.getUserId()).eq(ImChatUserFriend::getFriendId, imChatUserFriend.getFriendId()))
                .or(wrapper -> wrapper.eq(ImChatUserFriend::getFriendId, imChatUserFriend.getUserId()).eq(ImChatUserFriend::getUserId, imChatUserFriend.getFriendId()))
                .count();
        if (count > 0) {
            //已经是好友了
            return MindCraftResult.success();
        }

        ImChatUserFriend imChatFriend = new ImChatUserFriend();
        imChatFriend.setUserId(imChatUserFriend.getUserId());
        imChatFriend.setFriendId(imChatUserFriend.getFriendId());

        baseMapper.insert(imChatFriend);

        UserFriendSku userFriendSku = new UserFriendSku();
        userFriendSku.setSkuId(imChatUserFriend.getSkuId());
        userFriendSku.setUserId(imChatFriend.getUserId());
        userFriendSku.setFriendId(imChatFriend.getFriendId());

        userFriendSkuMapper.insert(userFriendSku);

        return MindCraftResult.success();
    }


    //根据用户id查找出对应的朋友
    @Override
    public MindCraftResult findNewsList(NewsListVo newsListVo) {

        NewsListVo page = lambdaQuery()
                .eq(ImChatUserFriend::getUserId, newsListVo.getUserId())
                .or()
//                .eq(ImChatUserFriend::getFriendId,newsListVo.getUserId())
                .page(newsListVo);

        List<ImChatUserFriend> records = newsListVo.getRecords();
        records.stream().forEach((item) -> {
            McUser user = userClient.getUser(item.getFriendId());
            LambdaQueryWrapper<UserFriendSku> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserFriendSku::getUserId, newsListVo.getUserId()).
                    or().eq(UserFriendSku::getFriendId,newsListVo.getUserId()).
                    and(wrapper1 ->
                            wrapper1.eq(UserFriendSku::getFriendId, item.getFriendId())
                                    .or()
                                    .eq(UserFriendSku::getFriendId,item.getUserId())
                    );
            UserFriendSku userFriendSku = userFriendSkuMapper.selectOne(wrapper);

            SkuInfo skuInfo = shopClient.getSkuInfoById(userFriendSku.getSkuId());

            //用户信息

            item.setNickName(user.getNickname());
            item.setUserPic(user.getUserpic());
//            item.setUserId(skuInfo.getUserId());

            //商品信息
            item.setImgUrl(skuInfo.getImgUrl());
            item.setPrice(skuInfo.getPrice());
            item.setPostAddress(skuInfo.getPostAddress());


            //从redis中获取 需要总条数，还有最后一条的内容 最后一条内容的时间
            String hashKey = "chat:" + newsListVo.getUserId() + ":" + item.getFriendId();
            String hashKey1 = "chat:" + item.getFriendId() + ":" + newsListVo.getUserId();

            List<Map<String, List<ImChatUserMessageVo>>> resultMapList = new ArrayList<>();
            List<ImChatUserMessageVo> resultList = new ArrayList<>();
            Map<String, List<ImChatUserMessageVo>> senderMap = new HashMap<>();
            Map<String, List<ImChatUserMessageVo>> receiverMap = new HashMap<>();

            if (redisTemplate.hasKey(hashKey)) {
                //如果是用户自己发送的信息
                List<String> chatRecordList = redisTemplate.opsForList().range(hashKey, 0, -1);

                List<ImChatUserMessageVo> chatRecordList1 = chatRecordList.stream()
                        .map(chatRecordJson -> JSON.parseObject(chatRecordJson, ImChatUserMessageVo.class))
                        .collect(Collectors.toList());

                senderMap.put("sendMessage", chatRecordList1);
            }
            if (redisTemplate.hasKey(hashKey1)) {
                //用户接收的信息
                List<String> chatRecordList = redisTemplate.opsForList().range(hashKey1, 0, -1);


                List<ImChatUserMessageVo> chatRecordList1 = chatRecordList.stream()
                        .map(chatRecordJson -> JSON.parseObject(chatRecordJson, ImChatUserMessageVo.class))
                        .collect(Collectors.toList());
                receiverMap.put("receiveMessage", chatRecordList1);
            }


            if (!redisTemplate.hasKey(hashKey) && !redisTemplate.hasKey(hashKey1)) {
                LambdaQueryWrapper<ImChatUserMessage> queryWrapper = new LambdaQueryWrapper<>();
                LambdaQueryWrapper<ImChatUserMessage> queryWrapper1 = new LambdaQueryWrapper<>();
                //查询自己发送的
                queryWrapper
                        .eq(ImChatUserMessage::getToId, item.getFriendId())
                        .eq(ImChatUserMessage::getFromId, newsListVo.getUserId());
                //查询发送给我的
                queryWrapper1
                        .eq(ImChatUserMessage::getToId, newsListVo.getUserId())
                        .eq(ImChatUserMessage::getFromId, item.getFriendId());

                //发送给自己的消息的列表
                List<ImChatUserMessage> chatRecordList = messageMapper.selectList(queryWrapper);
                //自己发送给别人消息的列表
                List<ImChatUserMessage> chatRecordList1 = messageMapper.selectList(queryWrapper1);

                List<ImChatUserMessageVo> messageVoList = chatRecordList.stream().map((chat) -> {
                    ImChatUserMessageVo imChatUserMessageVo = new ImChatUserMessageVo();
                    imChatUserMessageVo.setContent(chat.getContent());
                    imChatUserMessageVo.setCreateTime(chat.getCreateTime());
                    imChatUserMessageVo.setId(chat.getId());

                    return imChatUserMessageVo;
                }).collect(Collectors.toList());
                senderMap.put("sendMessage", messageVoList);

                List<ImChatUserMessageVo> messageVoList1 = chatRecordList1.stream().map((chat) -> {
                    ImChatUserMessageVo imChatUserMessageVo = new ImChatUserMessageVo();
                    imChatUserMessageVo.setContent(chat.getContent());
                    imChatUserMessageVo.setCreateTime(chat.getCreateTime());
                    imChatUserMessageVo.setId(chat.getId());

                    return imChatUserMessageVo;
                }).collect(Collectors.toList());
                receiverMap.put("receiveMessage", messageVoList1);


            }
            resultMapList.add(senderMap);
            resultMapList.add(receiverMap);

            // 比较器：按照创建时间升序排序
            Comparator<ImChatUserMessageVo> comparator = Comparator.comparing(ImChatUserMessageVo::getCreateTime);


            //数据库查询
            List<ImChatUserMessageVo> sendMessage = null;
            ImChatUserMessageVo imChatUserMessageVo = null;
            List<ImChatUserMessageVo> receiveMessage = null;
            ImChatUserMessageVo imChatUserMessageVo1 = null;
            for (Map<String, List<ImChatUserMessageVo>> stringListMap : resultMapList) {


                if (stringListMap.containsKey("sendMessage")) {

                    sendMessage = stringListMap.get("sendMessage");
                    imChatUserMessageVo = sendMessage.stream().max(comparator)
                            .orElse(null);
                } else if (stringListMap.containsKey("receiveMessage")) {
                    receiveMessage = stringListMap.get("receiveMessage");

                    imChatUserMessageVo1 = receiveMessage.stream().max(comparator)
                            .orElse(null);


                }


            }

            ImChatUserMessageVo maxImChatUserMessageVo = new ImChatUserMessageVo();
            Integer messagesize = 0;
            if(imChatUserMessageVo != null && imChatUserMessageVo1 ==null){
                maxImChatUserMessageVo = imChatUserMessageVo;
                messagesize = sendMessage.size();
            }else if(imChatUserMessageVo1 != null && imChatUserMessageVo ==null){
                maxImChatUserMessageVo = imChatUserMessageVo1;
                messagesize = receiveMessage.size();
            }else{
                //有全不是空和全是空的两种情况
                if(imChatUserMessageVo1 == null && imChatUserMessageVo ==null){
                    //如果全是空
                    maxImChatUserMessageVo.setContent("");
                    //TODO 设置时间
                    maxImChatUserMessageVo.setCreateTime(null);
                    messagesize = 0;
                }else{
                    maxImChatUserMessageVo = comparator.compare(imChatUserMessageVo, imChatUserMessageVo1) > 0 ? imChatUserMessageVo : imChatUserMessageVo1;
                    messagesize = sendMessage.size() + receiveMessage.size();
                }

            }
            item.setContent(maxImChatUserMessageVo.getContent());
            item.setCreateTime(maxImChatUserMessageVo.getCreateTime());
            item.setNewsCount(messagesize);


        });

        return MindCraftResult.success(page);
    }
}
